app.controller("chatController", function ($scope, $rootScope, $http, $location) {
    var filePath = '/zzlp/resources/upload/chatFile/';
    var h1 = $location.host();
    var h2 = "ws://" + h1 + ":80/zzlp/socketServer";
    var dataStream = new WebSocket(h2);
    $scope.groupAvaSrc = '/zzlp/img/groupAvatar.jpg';

    function cut(str) {
        if (str.length < 10) {
            return str;
        } else {
            str = str.substr(0, 10);
            str += "..";
            return str;
        }

    }


    var collection = [];
    $http({
        method: 'GET',
        url: '../searchUserId',

    }).then(function successCallback(response) {

        localStorage.setItem("userId", response.data);

    }, function errorCallback(respoonse) {

    });


    dataStream.onclose = function () {
        alert("登录超时，请重新登录");
        window.location = "/zzlp/html/login.html";
    }


    dataStream.onmessage = function (msg) {

        var message = JSON.parse(msg.data);
        if (message.isGroup == 1) {

            if ($("#targetId").html() == message.groupId) {
                $http({
                    method: 'POST',
                    url: '../Group/readGroupMessage',
                    data: {groupId: message.groupId}
                }).then(function successCallback(response) {

                }, function errorCallback(respoonse) {

                });
                var temp = "#" + message.groupId + "LastMessage";
                if (message.type == "text") {
                    $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                    $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'> " + duEncode(message.msg) + " </div></span> </div> </div>");
                    $(temp).html(cut(duEncode(message.msg)));
                }
                else if (message.type == "img") {
                    // $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                    // $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                    $("#chatView").append("<div class='sender'  style='display: none' word-wrap:break-word><div><img   class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' src='" + filePath + message.msg + "'/></div></span> </div> </div>");

                    setTimeout(function () {
                        $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                        $("#chatView").append("<div class='sender'  word-wrap:break-word><div><img   class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                        var div = document.getElementById("chatView");
                        div.scrollTop = div.scrollHeight;
                        localStorage.setItem(localStorage.getItem("userId") + "_" + $("#targetId").html(), $("#chatView").html());

                    }, 100);

                    $(temp).html("[图片]");
                } else if (message.type == "file") {
                    $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                    $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatIcon' src='" + message.icon + "'/>&nbsp;<a href='" + filePath + message.msg + "' download='"+(message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length)+"'>下载</a><p>" + (message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length) + "</p></div></span> </div> </div>");
                    $(temp).html("[文件]");
                }
                localStorage.setItem(localStorage.getItem("userId") + "_" + $("#targetId").html(), $("#chatView").html());
                var div = document.getElementById("chatView");
                div.scrollTop = div.scrollHeight;

            } else {
                if ((localStorage.getItem(localStorage.getItem("userId") + "_" + message.groupId) == "") || (localStorage.getItem(localStorage.getItem("userId") + "_" + message.groupId) == null) || (localStorage.getItem(localStorage.getItem("userId") + "_" + message.groupId) == "undefined")) {
                    alert("您被邀请加入新的群聊");
                    window.location.reload();
                    localStorage.setItem(localStorage.getItem("userId") + "_" + message.groupId, "");
                }
                $http({
                    method: 'POST',
                    url: '../Group/searchUnreadMsgCount',
                    data: {groupId: message.groupId}
                }).then(function successCallback(response) {
                    var Msgcount = "#" + message.groupId + "count";
                    $(Msgcount).text(response.data);
                    $(Msgcount).css("display", "");
                }, function errorCallback(respoonse) {

                });
                var temp = "#" + message.groupId + "LastMessage";
                $(temp).html(cut(duEncode(message.msg)));
                $("#tempChatView").html(localStorage.getItem(localStorage.getItem("userId") + "_" + message.groupId));
                if (message.type == "text") {
                    $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                    $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'> " + duEncode(message.msg) + " </div></span> </div> </div>");
                    $(temp).html(cut(duEncode(message.msg)));
                }
                else if (message.type == "img") {
                    $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                    $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                    $(temp).html("[图片]");
                } else if (message.type == "file") {
                    $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                    $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatIcon' src='" + message.icon + "'/>&nbsp;<a href='" + filePath + message.msg + "' download='"+(message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length)+"'>下载</a><p>" + (message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length) + "</p></div></span> </div> </div>");
                    $(temp).html("[文件]");
                }
                localStorage.setItem(localStorage.getItem("userId") + "_" + message.groupId, $("#tempChatView").html());
                $("#tempChatView").html("");
            }
        }
        else {
            if ($("#targetId").html() == message.fromId) {
                var temp = "#" + message.fromId + "LastMessage";
                if (message.type == "text") {
                    $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                    $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'> " + duEncode(message.msg) + " </div></span> </div> </div>");
                    $(temp).html(cut(duEncode(message.msg)));
                }
                else if (message.type == "img") {
                    $("#chatView").append("<div class='sender' style='display: none' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                    setTimeout(function () {
                        $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                        $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                        var div = document.getElementById("chatView");
                        div.scrollTop = div.scrollHeight;
                        localStorage.setItem(localStorage.getItem("userId") + "_" + $("#targetId").html(), $("#chatView").html());

                    }, 100);
                    $(temp).html("[图片]");
                } else if (message.type == "file") {
                    $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                    $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatIcon' src='" + message.icon + "'/>&nbsp;<a href='" + filePath + message.msg + "' download='"+(message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length)+"'>下载</a><p>" + (message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length) + "</p></div></span> </div> </div>");
                    $(temp).html("[文件]");
                }
                localStorage.setItem(localStorage.getItem("userId") + "_" + $("#targetId").html(), $("#chatView").html());
                var div = document.getElementById("chatView");
                div.scrollTop = div.scrollHeight;
                var id = $("#targetId").html();
                $http({
                    method: 'POST',
                    data: {
                        fromId: id,
                    },
                    url: '../readMessageEnd'
                }).then(function successCallback(response) {

                }, function errorCallback(response) {
                    // 请求失败执行代码
                });
            } else {
                if ((localStorage.getItem(localStorage.getItem("userId") + "_" + message.fromId) == "") || (localStorage.getItem(localStorage.getItem("userId") + "_" + message.fromId) == null)) {
                    localStorage.setItem(localStorage.getItem("userId") + "_" + message.fromId, "");
                }
                var temp = "#" + message.fromId + "LastMessage";
                $(temp).html(cut(duEncode(message.msg)));
                var temp1 = "#" + message.fromId + "red";
                $(temp1).show();
                $(temp1).html($(temp1).html() * 1 + 1 * 1);
                $("#tempChatView").html(localStorage.getItem(localStorage.getItem("userId") + "_" + message.fromId));
                if (message.type == "text") {
                    $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                    $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'> " + duEncode(message.msg) + " </div></span> </div> </div>");
                    $(temp).html(cut(duEncode(message.msg)));
                }
                else if (message.type == "img") {
                    $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                    $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                    $(temp).html("[图片]");
                } else if (message.type == "file") {
                    $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                    $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatIcon' src='" + message.icon + "'/>&nbsp;<a href='" + filePath + message.msg + "' download='"+(message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length)+"'>下载</a><p>" + (message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length) + "</p></div></span> </div> </div>");
                    $(temp).html("[文件]");
                }

                localStorage.setItem(localStorage.getItem("userId") + "_" + message.fromId, $("#tempChatView").html());
                $("#tempChatView").html("");
            }
            //alert(msg.data);
        }
        collection.push(msg.data);
        $rootScope.$apply();
    }

    $rootScope.showDetail = function (name, time, content, img, avatar) {
        $rootScope.visiable = true;

        $rootScope.DName = name;
        $rootScope.DTime = time;
        $rootScope.DContent = content;
        $rootScope.DImgs = img;
        $rootScope.DAvatar = avatar;

        $("#publishsaysay").hide();
        $("#DetailDiv").show();


        $scope.changePic = function ($event) {
            var img = $event.srcElement || $event.target;
            angular.element("#bigimage")[0].src = img.src;
            angular.element("#js-imgview")[0].style.display = "block";
            angular.element("#js-imgview-mask")[0].style.display = "block";
        }
        //点击图片时放小显示图片
        $scope.closePic = function () {
            angular.element("#js-imgview")[0].style.display = "none";
            angular.element("#js-imgview-mask")[0].style.display = "none";

        }

    }
    // function userTextEncode($str){
    //     if(!is_string($str))return $str;
    //     if(!$str || $str=='undefined')return '';
    //
    //     $tmpStr = json_encode($text); //暴露出unicode
    //     $tmpStr = preg_replace("#(\\\ue[0-9a-f]{3})#ie","addslashes('\\1')",$tmpStr); //将emoji的unicode留下，其他不动
    //     $text = json_decode($tmpStr);
    //     return $text;

    function p(s) {
        return s < 10 ? '0' + s : s;
    }

    $scope.sendMsg = function () {
        var msg = $("#chatBox").text();
        if (msg.length == 0) {
            alert("消息不能为空");
            $("#chatBox").text("");
            return;
        }

        var encodeMsg = encode(msg);
        // msg=userTextEncode(msg);
        var myDate = new Date();
//获取当前年
        var year = myDate.getFullYear();
//获取当前月
        var month = myDate.getMonth() + 1;
//获取当前日
        var date = myDate.getDate();
        var h = myDate.getHours();       //获取当前小时数(0-23)
        var m = myDate.getMinutes();     //获取当前分钟数(0-59)
        var s = myDate.getSeconds();

        var now = year + '-' + p(month) + "-" + p(date) + " " + p(h) + ':' + p(m) + ":" + p(s);

        if ($("#targetId").html() > 100000) {

            /*$http({
                method: 'GET',
                url: '../Group/judgeUserConnection',
            }).then(function successCallback(response) {
                alert(response.data);
                if(response.data == false){
                    alert("您已断开连接，请重新登录");
                    window.location="/zzlp/html/login.html";
                    return;
                }
            }, function errorCallback(response) {
                alert("您已断开连接，请重新登录");
                window.location="/zzlp/html/login.html";
                return;
            });*/
            $http({
                method: 'POST',
                url: '../Group/sendToGroup',
                data: {
                    toId: 0,
                    msg: encodeMsg,
                    time: now,
                    type: "text",
                    isGroup: 1,
                    groupId: $("#targetId").html()
                },
            }).then(function successCallback(response) {

                //$scope.users=response.data;
                // 请求成功执行代码
            }, function errorCallback(response) {
                // 请求失败执行代码
            });
        }

        else {
            $http({
                method: 'POST',
                url: '../sendToUser',
                data: {
                    toId: $("#targetId").html(),
                    msg: encodeMsg,
                    time: now,
                    type: "text",
                    isGroup: 0,
                    groupId: 0
                },
            }).then(function successCallback(response) {

                //$scope.users=response.data;
                // 请求成功执行代码
            }, function errorCallback(response) {
                // 请求失败执行代码
            });
        }
        $scope.id = $("#targetId").html();

        var temp = "#" + $("#targetId").html() + "LastMessage";

        $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + now + " &nbsp</span></div>")
        $("#chatView").append("<div class='receiver' word-wrap:break-word><div><img class='avatar' src='" + $scope.userInfos[0].photo + "'></div><div word-wrap:break-word><div class='right_triangle'></div><span><div class='wrap'> " + msg + " </div></span> </div> </div>");
        $(temp).html(cut(msg));


        // localStorage.setItem($("#targetId").html(), "");
        localStorage.setItem(localStorage.getItem("userId") + "_" + $("#targetId").html(), $("#chatView").html());
        var div = document.getElementById("chatView");
        div.scrollTop = div.scrollHeight;


        $("#chatBox").html("");
    }

    // }


    $(document).ready(function () {

        function p(s) {
            return s < 10 ? '0' + s : s;
        }


        $(document).keyup(function (evnet) {
            var act = document.activeElement.id;
            if ((evnet.keyCode == '13') && (act == "chatBox")) {
                var msg = $("#chatBox").text();
                if (msg.length == 0) {
                    alert("消息不能为空");
                    $("#chatBox").text("");
                    return;
                }

                var encodeMsg = encode(msg);
                // msg=userTextEncode(msg);
                var myDate = new Date();
//获取当前年
                var year = myDate.getFullYear();
//获取当前月
                var month = myDate.getMonth() + 1;
//获取当前日
                var date = myDate.getDate();
                var h = myDate.getHours();       //获取当前小时数(0-23)
                var m = myDate.getMinutes();     //获取当前分钟数(0-59)
                var s = myDate.getSeconds();

                var now = year + '-' + p(month) + "-" + p(date) + " " + p(h) + ':' + p(m) + ":" + p(s);

                if ($("#targetId").html() > 100000) {

                    /*$http({
                        method: 'GET',
                        url: '../Group/judgeUserConnection',
                    }).then(function successCallback(response) {
                        alert(response.data);
                        if(response.data == false){
                            alert("您已断开连接，请重新登录");
                            window.location="/zzlp/html/login.html";
                            return;
                        }
                    }, function errorCallback(response) {
                        alert("您已断开连接，请重新登录");
                        window.location="/zzlp/html/login.html";
                        return;
                    });*/
                    $http({
                        method: 'POST',
                        url: '../Group/sendToGroup',
                        data: {
                            toId: 0,
                            msg: encodeMsg,
                            time: now,
                            type: "text",
                            isGroup: 1,
                            groupId: $("#targetId").html()
                        },
                    }).then(function successCallback(response) {

                        //$scope.users=response.data;
                        // 请求成功执行代码
                    }, function errorCallback(response) {
                        // 请求失败执行代码
                    });
                }

                else {
                    $http({
                        method: 'POST',
                        url: '../sendToUser',
                        data: {
                            toId: $("#targetId").html(),
                            msg: encodeMsg,
                            time: now,
                            type: "text",
                            isGroup: 0,
                            groupId: 0
                        },
                    }).then(function successCallback(response) {

                        //$scope.users=response.data;
                        // 请求成功执行代码
                    }, function errorCallback(response) {
                        // 请求失败执行代码
                    });
                }
                $scope.id = $("#targetId").html();

                var temp = "#" + $("#targetId").html() + "LastMessage";

                $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + now + " &nbsp</span></div>")
                $("#chatView").append("<div class='receiver' word-wrap:break-word><div><img class='avatar' src='" + $scope.userInfos[0].photo + "'></div><div word-wrap:break-word><div class='right_triangle'></div><span><div class='wrap'> " + msg + " </div></span> </div> </div>");
                $(temp).html(cut(msg));


                // localStorage.setItem($("#targetId").html(), "");
                localStorage.setItem(localStorage.getItem("userId") + "_" + $("#targetId").html(), $("#chatView").html());
                var div = document.getElementById("chatView");
                div.scrollTop = div.scrollHeight;


                $("#chatBox").html("");
            }
        });


    });


    $scope.createLog = function () {

        if ($("#targetId").html() > 100000) {
            $http({
                method: 'POST',
                url: '../Group/searchAllGroupMsg',
                data: {
                    groupId: $("#targetId").html(),
                },
            }).then(function successCallback(response) {
                $("<a href='" + response.data.path + "' download>Download</a>")[0].click();
            }, function errorCallback(response) {
                // 请求失败执行代码
            });
        } else {
            $http({
                method: 'POST',
                url: '../searchAllMessage',
                data: {
                    toId: $("#targetId").html(),
                },
            }).then(function successCallback(response) {
                $("<a href='" + response.data.path + "' download>Download</a>")[0].click();
                //$scope.users=response.data;
                // 请求成功执行代码
            }, function errorCallback(response) {

                // 请求失败执行代码
            });
        }

    }


    $scope.file = "";

    $scope.selectFile = function () {
        $("#file").trigger("click");


    }
    $scope.change = function () {
        var maxsize = 2 * 1024 * 1024;//2M
        var v = $("#file")[0].files[0].size;

        if (v >= maxsize) {
            alert("文件大小不得超过2M");

            var obj = document.getElementById("file");
            obj.outerHTML = obj.outerHTML;
            return;
        }
        var fileName = $("#file").val();
        var arr1 = ["jpg", "png"];
        var arr2 = ["doc", "docx", "xls", "txt", "zip", "rar"];
        var index = fileName.lastIndexOf(".");
        var ext = fileName.substr(index + 1);

        for (var i = 0; i < arr1.length; i++) {
            if (ext == arr1[i]) {
                $scope.submitimg(); //一旦找到合适的，立即退出循环
                var obj = document.getElementById("file");
                obj.outerHTML = obj.outerHTML;
                break;
            }
        }
        for (var i = 0; i < arr2.length; i++) {
            if (ext == arr2[i]) {
                $scope.submitfile(); //一旦找到合适的，立即退出循环
                var obj = document.getElementById("file");
                obj.outerHTML = obj.outerHTML;
                break;
            }
        }

    };

    function p(s) {
        return s < 10 ? '0' + s : s;
    }

    $scope.submitfile = function () {


        var myDate = new Date();
//获取当前年
        var year = myDate.getFullYear();
//获取当前月
        var month = myDate.getMonth() + 1;
//获取当前日
        var date = myDate.getDate();
        var h = myDate.getHours();       //获取当前小时数(0-23)
        var m = myDate.getMinutes();     //获取当前分钟数(0-59)
        var s = myDate.getSeconds();

        var now = year + '-' + p(month) + "-" + p(date) + " " + p(h) + ':' + p(m) + ":" + p(s);
        var fd = new FormData();
        var files = document.querySelector('input[name="files"]').files;

        if ($("#targetId").html() > 100000) {
            fd.append("files", files[0]);
            fd.append("groupId", $("#targetId").html());
            fd.append("time", now);
            fd.append("type", "file");

            $http({
                method: 'POST',
                url: '../Group/sendFileToGroup',
                data: fd,
                headers: {'Content-Type': undefined},

            }).then(function successCallback(response) {

                var message = response.data;
                // alert(message.msg);
                //alert(message.icon);
                var temp = "#" + $("#targetId").html() + "LastMessage";
                $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                $("#chatView").append("<div class='receiver' word-wrap:break-word><div><img class='avatar' src='" + $scope.userInfos[0].photo + "'></div><div word-wrap:break-word><div class='right_triangle'></div><span><div class='wrap'><img class='chatIcon' src='" + message.icon + "'/>&nbsp;<a href='" + filePath + message.msg + "' download='"+(message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length)+"'>下载</a><p>" + (message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length) + "</p></div></span> </div> </div>");
                $(temp).html("[文件]");
                localStorage.setItem(localStorage.getItem("userId") + "_" + $("#targetId").html(), $("#chatView").html());
                var div = document.getElementById("chatView");
                div.scrollTop = div.scrollHeight;
            }, function errorCallback(response) {
                alert("error")
            });
        }
        else {
            fd.append("files", files[0]);
            fd.append("toId", $("#targetId").html());
            fd.append("time", now);
            fd.append("type", "file");

            $http({
                method: 'POST',
                url: '../sendFileToUser',
                data: fd,
                headers: {'Content-Type': undefined},

            }).then(function successCallback(response) {

                var message = response.data;
                // alert(message.msg);

                var temp = "#" + $("#targetId").html() + "LastMessage";
                $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                $("#chatView").append("<div class='receiver' word-wrap:break-word><div><img class='avatar' src='" + $scope.userInfos[0].photo + "'></div><div word-wrap:break-word><div class='right_triangle'></div><span><div class='wrap'><img class='chatIcon' src='" + message.icon + "'/>&nbsp;<a href='" + filePath + message.msg + "' download='"+(message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length)+"'>下载</a><p>" + (message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length) + "</p></div></span> </div> </div>");
                $(temp).html("[文件]");
                localStorage.setItem(localStorage.getItem("userId") + "_" + $("#targetId").html(), $("#chatView").html());
                var div = document.getElementById("chatView");
                div.scrollTop = div.scrollHeight;
            }, function errorCallback(response) {
                alert("error")
            });
        }
    }

    $scope.submitimg = function () {


        var myDate = new Date();
//获取当前年
        var year = myDate.getFullYear();
//获取当前月
        var month = myDate.getMonth() + 1;
//获取当前日
        var date = myDate.getDate();
        var h = myDate.getHours();       //获取当前小时数(0-23)
        var m = myDate.getMinutes();     //获取当前分钟数(0-59)
        var s = myDate.getSeconds();

        var now = year + '-' + p(month) + "-" + p(date) + " " + p(h) + ':' + p(m) + ":" + p(s);
        var fd = new FormData();
        var files = document.querySelector('input[name="files"]').files;

        if ($("#targetId").html() > 100000) {
            fd.append("files", files[0]);
            fd.append("groupId", $("#targetId").html());
            fd.append("time", now);
            fd.append("type", "img");

            $http({
                method: 'POST',
                url: '../Group/sendImgToGroup',
                data: fd,
                headers: {'Content-Type': undefined},

            }).then(function successCallback(response) {

                var message = response.data;
                // alert(message.msg);
                var temp = "#" + $("#targetId").html() + "LastMessage";
                $("#chatView").append("<div class='receiver' id='imgtemp' style='display: none'  word-wrap:break-word><div><img    class='avatar' src='" + $scope.userInfos[0].photo + "'></div><div word-wrap:break-word><div class='right_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' id='img' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                setTimeout(function () {
                    $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                    $("#chatView").append("<div class='receiver' word-wrap:break-word><div><img    class='avatar' src='" + $scope.userInfos[0].photo + "'></div><div word-wrap:break-word><div class='right_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' id='img123' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                    var div = document.getElementById("chatView");
                    div.scrollTop = div.scrollHeight;

                    localStorage.setItem(localStorage.getItem("userId") + "_" + $("#targetId").html(), $("#chatView").html());

                }, 100);
                $(temp).html("[图片]");
                var div = document.getElementById("chatView");
                div.scrollTop = div.scrollHeight;
            }, function errorCallback(response) {
                alert("error")
            });
        }
        else {
            fd.append("files", files[0]);
            fd.append("toId", $("#targetId").html());
            fd.append("time", now);
            fd.append("type", "img");

            $http({
                method: 'POST',
                url: '../sendImgToUser',
                data: fd,
                headers: {'Content-Type': undefined},

            }).then(function successCallback(response) {

                var message = response.data;
                var temp = "#" + $("#targetId").html() + "LastMessage";
                $("#chatView").append("<div class='receiver' id='imgtemp' style='display: none'  word-wrap:break-word><div><img    class='avatar' src='" + $scope.userInfos[0].photo + "'></div><div word-wrap:break-word><div class='right_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' id='img' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                setTimeout(function () {
                    $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                    $("#chatView").append("<div class='receiver' word-wrap:break-word><div><img    class='avatar' src='" + $scope.userInfos[0].photo + "'></div><div word-wrap:break-word><div class='right_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' id='img123' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                    localStorage.setItem(localStorage.getItem("userId") + "_" + $("#targetId").html(), $("#chatView").html());
                    var div = document.getElementById("chatView");
                    div.scrollTop = div.scrollHeight;
                }, 100);
                //     $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                //     $("#chatView").append("<div class='receiver' word-wrap:break-word><div><img    class='avatar' src='" + $scope.userInfos[0].photo + "'></div><div word-wrap:break-word><div class='right_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' id='img123' alt=''  src='getImgByFileName.do'/></div></span> </div> </div>");
                $(temp).html("[图片]");
                // localStorage.setItem(localStorage.getItem("userId") + "_" + $("#targetId").html(), $("#chatView").html());
                // $("#chatView").html(localStorage.getItem(localStorage.getItem("userId") + "_" + $("#targetId").html()));
                var div = document.getElementById("chatView");
                div.scrollTop = div.scrollHeight;
            }, function errorCallback(response) {
                alert("error");
            });
        }
    }


    // $("#file").on('change', function () {
    //     alert($("#file").val())
    //
    // })

    function selectFile() {

        //触发 文件选择的click事件
        $("#file").trigger("click");

        //其他code如 alert($("#file").attr("value"))
    }

    /* 获取 文件的路径 ，用于测试*/
    function getFilePath() {

    }


    // $scope.emojis = getEmoji();
    $scope.emojis = "";
    $scope.addEmojiToChatBox = function (emoji) {

        $("#chatBox").append(emoji);

    }


    $scope.addEmoji = function () {

        $("#chatbackground").show();


        if ($("#emoji").css("display") == "none") {

            $("#emoji").show();


        } else {
            $("#emoji").css("display", "none");

        }
        $scope.emojis = getEmoji();

    }

    $scope.$on('$viewContentLoaded', function () {

        $http({
            method: 'GET',
            url: '../Group/searchUserInfos',
        }).then(function successCallback(response) {
            $scope.userInfos = response.data;
            for (var i = 0; i < $scope.userInfos.length; i++) {
                localStorage.setItem("ava" + $scope.userInfos[i].user_id, $scope.userInfos[i].photo);
            }
        }, function errorCallback(respoonse) {
        });

        $http({
            method: 'GET',
            url: '../Group/searchAllGroup'
        }).then(function successCallback(response) {
            $scope.groupInfos = response.data;

            for (var i = 0; i < $scope.groupInfos.length; i++) {
                $scope.groupInfos[i].lastMsg = duEncode($scope.groupInfos[i].lastMsg);
                var id = $scope.groupInfos[i].id;

                if ((localStorage.getItem(localStorage.getItem("userId") + "_" + id) == null) || (localStorage.getItem(localStorage.getItem("userId") + "_" + id) == "undefined")) {
                    localStorage.setItem(localStorage.getItem("userId") + "_" + id, "");
                }

                    $("#chatView").html(localStorage.getItem(localStorage.getItem("userId") + "_" + id));

                $("#tempChatView").html("");

                for (var j = 0; j < $scope.groupInfos[i].unReadMsgs.length; j++) {
                    var message = $scope.groupInfos[i].unReadMsgs[j];
                    var temp = "#" + message.groupId + "LastMessage";
                    if (message.type == "text") {
                        $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                        $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'> " + duEncode(message.msg) + " </div></span> </div> </div>");
                        $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                        $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'> " + duEncode(message.msg) + " </div></span> </div> </div>");
                        $(temp).html(cut(duEncode(message.msg)));
                    }
                    else if (message.type == "img") {
                        $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                        $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg'  ng-click='changePic($event)' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                        $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                        $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                        $(temp).html("[图片]");
                    } else if (message.type == "file") {
                        $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                        $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatIcon' src='" + message.icon + "'/>&nbsp;<a href='" + filePath + message.msg + "' download='"+(message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length)+"'>下载</a><p>" + (message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length) + "</p></div></span> </div> </div>");
                        $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                        $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatIcon' src='" + message.icon + "'/>&nbsp;<a href='" + filePath + message.msg + "' download='"+(message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length)+"'>下载</a><p>" + (message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length) + "</p></div></span> </div> </div>");
                        $(temp).html("[文件]");
                    }
                }
                if (localStorage.getItem(localStorage.getItem("userId") + "_" + id).indexOf($("#tempChatView").html()) >= 0) {
                    //do nothing
                } else {
                    localStorage.setItem(localStorage.getItem("userId") + "_" + id, $("#chatView").html());
                }
                $("#chatView").html("");
                $("#tempChatView").html("");
                var div = document.getElementById("chatView");
                div.scrollTop = div.scrollHeight;
            }
        }, function errorCallback(response) {
            // 请求失败执行代码
        });

        $http({
            method: 'GET',
            url: '../searchUsers'
        }).then(function successCallback(response) {

            $scope.users = response.data;
            for (var i = 0; i < $scope.users.length; i++) {
                $scope.users[i].lastMessage = duEncode($scope.users[i].lastMessage);
                var id = $scope.users[i].userId;
                if ((localStorage.getItem(localStorage.getItem("userId") + "_" + id) == null) || (localStorage.getItem(localStorage.getItem("userId") + "_" + id) == "undefined")) {
                    localStorage.setItem(localStorage.getItem("userId") + "_" + id, "");
                }

                    $("#chatView").html(localStorage.getItem(localStorage.getItem("userId") + "_" + id));


                $("#tempChatView").html("");

                for (var j = 0; j < $scope.users[i].chatList.length; j++) {
                    var message = $scope.users[i].chatList[j];
                    var temp = "#" + message.fromId + "LastMessage";

                    if (message.type == "text") {

                        $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                        $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'> " + duEncode(message.msg) + " </div></span> </div> </div>");
                        $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                        $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'> " + duEncode(message.msg) + " </div></span> </div> </div>");
                        $(temp).html(cut(duEncode(message.msg)));
                    }
                    else if (message.type == "img") {
                        $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                        $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg'  ng-click='changePic($event)' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                        $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>");
                        $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatImg' ng-click='changePic($event)' src='" + filePath + message.msg + "'/></div></span> </div> </div>");
                        $(temp).html("[图片]");
                    } else if (message.type == "file") {
                        $("#chatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                        $("#chatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatIcon' src='" + message.icon + "'/>&nbsp;<a href='" + filePath + message.msg + "' download='"+(message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length)+"'>下载</a><p>" + (message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length) + "</p></div></span> </div> </div>");
                        $("#tempChatView").append("<div class='time'><span class='spanTime'>&nbsp" + message.time + " &nbsp</span></div>")
                        $("#tempChatView").append("<div class='sender' word-wrap:break-word><div><img class='avatar' src='" + localStorage.getItem("ava" + message.fromId) + "'></div><div word-wrap:break-word><div class='left_triangle'></div><span><div class='wrap'><img class='chatIcon' src='" + message.icon + "'/>&nbsp;<a href='" + filePath + message.msg + "' download='"+(message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length)+"'>下载</a><p>" + (message.msg).substring((message.msg).indexOf("_")+1,(message.msg).length) + "</p></div></span> </div> </div>");
                        $(temp).html("[文件]");
                    }
                }
                if (localStorage.getItem(localStorage.getItem("userId") + "_" + id).indexOf($("#tempChatView").html()) >= 0) {
                    //do nothing
                } else {
                    localStorage.setItem(localStorage.getItem("userId") + "_" + id, $("#chatView").html());
                }
                $("#chatView").html("");
                $("#tempChatView").html("");
                var div = document.getElementById("chatView");
                div.scrollTop = div.scrollHeight;
            }
            // 请求成功执行代码
        }, function errorCallback(response) {
            // 请求失败执行代码
        });
    });

    $scope.openChatBox = function (id, name, $event) {

        $("#coverDiv").hide();
        var temp1 = "#" + id + "div";
        $('.Layer22').css('background', 'none');
        $(temp1).css('background', 'gray');

        if (id > 100000) {
            var Msgcount = "#" + id + "count";
            $(Msgcount).hide();

            $http({
                method: 'POST',
                url: '../Group/readGroupMessage',
                data: {groupId: id}
            }).then(function successCallback(response) {

            }, function errorCallback(respoonse) {

            });

        }
        else {
            var temp = "#" + id + "red";
            $(temp).hide();
            $(temp).html("");

            $http({
                method: 'POST',
                data: {
                    fromId: id,
                },
                url: '../readMessageEnd'
            }).then(function successCallback(response) {

            }, function errorCallback(response) {
                // 请求失败执行代码
            });

        }


        $("#chatBox").css("display", 'block')
        $("#targetName").html(name);
        $("#targetId").html(id);
        if ((localStorage.getItem(localStorage.getItem("userId") + "_" + id) == "") || (localStorage.getItem(localStorage.getItem("userId") + "_" + id) == null)) {
            $("#chatView").html("");
        } else {

            // alert(localStorage.getItem(id));
            $("#chatView").html("<div style='display:none'>" + localStorage.getItem(localStorage.getItem("userId") + "_" + id) + "</div>");

            setTimeout(function () {
                $("#chatView").html(localStorage.getItem(localStorage.getItem("userId") + "_" + id));
                var div = document.getElementById("chatView");
                div.scrollTop = div.scrollHeight;
            }, 100);
        }
        var div = document.getElementById("chatView");
        div.scrollTop = div.scrollHeight;
    }


    $scope.showCheckDiv = function () {
        $("#checkDiv").toggle();
    }

    $scope.buildGroup = function () {
        var arrayObj = new Array();
        for (var i in $scope.users) {
            var id = $scope.users[i].userId;
            var temp = "#" + id + "checked";
            if ($(temp).prop('checked')) {
                /*alert(id);*/
                arrayObj.push(id);
            }
        }
        if (arrayObj.length == 0) {
            alert("请至少选择一名群组成员！");
            return;
        }
        $http({
            method: 'POST',
            traditional: true,
            dataType: "json",
            data: {
                users: arrayObj
            },
            url: '../Group/createGroup'
        }).then(function successCallBack(response) {
            alert("创建成功");
            for (var i in $scope.users) {
                var id = $scope.users[i].userId;
                var temp = "#" + id + "checked";
                if ($(temp).prop('checked')) {
                    /*alert(id);*/
                    $(temp).prop('checked', false)
                }
            }
            $("#checkDiv").hide();
            window.location.reload();
        }, function errorCallBack(response) {
            alert("创建失败");
        })
    }

})


